package com.cmdb.system.utils;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class JsonRepairAndDecode {

    private static final Pattern ENCODED_PATTERN = Pattern.compile("\\\\x([0-9a-fA-F]{2})");

    /**
            * 修复并解码问题JSON
     *
             * @param problemJson 有格式问题的原始JSON字符串
     * @return 修复后的JSON对象
     */
    public static Map<String, Object> decodeProblemJson(String problemJson) {
        try {
            // 1. 预处理：修复引号问题和多余反斜杠
            String cleanJson = problemJson
                    .replaceAll("\\\\\"", "\"")      // 修复转义引号
                    .replaceAll("\\\\x", "\\\\x")   // 保持有效转义
                    .replaceAll("\\{\\\\", "{")      // 修复开头多余反斜杠
                    .replaceAll("\"\\\\,", "\",")   // 修复逗号前多余反斜杠
                    .replaceAll("\"\\}", "\"}");    // 修复对象结尾问题

            // 2. 提取并转换所有十六进制编码字段
            cleanJson = convertEncodedStrings(cleanJson);

            // 3. 解析为标准JSON对象
            ObjectMapper mapper = new ObjectMapper();
            return mapper.readValue(cleanJson, new TypeReference<Map<String, Object>>(){});

        } catch (Exception e) {
            // 错误处理：返回带诊断信息的Map
            Map<String, Object> errorMap = new HashMap<>();
            errorMap.put("error", "JSON解析失败");
            errorMap.put("reason", e.getMessage());
            errorMap.put("original", problemJson.length() > 200 ?
                    problemJson.substring(0, 200) + "..." : problemJson);
            return errorMap;
        }
    }

    /**
            * 转换所有包含\x序列的字符串
     */
    private static String convertEncodedStrings(String json) {
        // 查找所有字段值中的转义序列
        Pattern valuePattern = Pattern.compile(":\"(.*?)\"");
        Matcher matcher = valuePattern.matcher(json);
        StringBuffer result = new StringBuffer();

        while (matcher.find()) {
            String originalValue = matcher.group(1);
            String decodedValue = decodeHexSequence(originalValue);
            matcher.appendReplacement(result, ":\"" + decodedValue + "\"");
        }
        matcher.appendTail(result);
        return result.toString();
    }

    /**
            * 核心解码方法
     */
    private static String decodeHexSequence(String input) {
        Matcher matcher = ENCODED_PATTERN.matcher(input);

        // 如果不是编码字符串直接返回
        if (!matcher.find()) return input;

        // 提取所有十六进制字节
        matcher.reset();
        StringBuilder hexBuilder = new StringBuilder();
        while (matcher.find()) {
            hexBuilder.append(matcher.group(1));
        }

        // 转换为UTF-8字符串
        return hexToUtf8(hexBuilder.toString());
    }

    /**
            * 十六进制转UTF-8字符串
     */
    private static String hexToUtf8(String hexString) {
        if (hexString.length() % 2 != 0) return "解码失败";

        try {
            byte[] bytes = new byte[hexString.length() / 2];
            for (int i = 0; i < bytes.length; i++) {
                int index = i * 2;
                bytes[i] = (byte) Integer.parseInt(
                        hexString.substring(index, index + 2), 16);
            }
            return new String(bytes, StandardCharsets.UTF_8);
        } catch (Exception e) {
            return "解码异常: " + e.getMessage();
        }
    }

    // 使用示例
    public static void main(String[] args) {
        // 图片中的原始问题JSON（带格式错误）
        String problemJson =
                "{\"msg\":\"\\xe4\\xba\\x8c\\xe7\\xbb\\xb4\\xe7\\xa0\\x81\\xe6\\x9c\\xaa\\xe7\\xa1\\xae\\xe8\\xae\\xa4\\\",\"traceId\":\"5fb68433d41882fb\",\"code\":\"USAP100010\"}";

        System.out.println("原始问题JSON:");
        System.out.println(problemJson);

        System.out.println("\n修复并解码后:");
        Map<String, Object> result = decodeProblemJson(problemJson);
        result.forEach((key, value) ->
                System.out.println(key + ": " + value)
        );
    }
}